package com.ideaction.utils.sms;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.io.CharStreams;
import org.apache.commons.codec.Charsets;

import javax.net.ssl.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * 短讯服务
 *
 * @author wh
 */
public class SmsKit {

    /**
     * 链接超时时间
     */
    public static String connectTimeout = "10000";
    /**
     * 读取超时时间
     */
    public static String readTimeout = "10000";
    /**
     * 你的accessKeyId
     */
    public static String accessKeyId = "LTAIJzU0acvZYCTa";
    /**
     * 你的accessKeySecret
     */
    public static String accessKeySecret = "5ZiOKPQWCkwnFt4DgMjVlTGKGYEEWY";
    /**
     * 地区ID
     */
    public static String regionId = "cn-hangzhou";
    /**
     * 签名
     */
    public static String signName = "末日远征";
    /**
     * 短信模板代码
     */
    public static String CHECK_TEMPLATECODE = "SMS_123665118", PASS_TEMPLATECODE = "SMS_136387248";
    /**
     * 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
     * "{\"name\":\"Tom\", \"code\":\"123\"}"
     */
    public static String CHECK_TEMPLATEPARAM = "{\"code\":\"%check_code\"}",
        PASS_TEMPLATEPARAM = "{\"content\":\"%content\"}";
    /**
     * 可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
     */
    public static String smsUpExtendCode = null;
    /**
     * 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
     */
    public static String outId = null;


    public static final String BLACK_KEY_CONTROL_LIMIT = "isv.BLACK_KEY_CONTROL_LIMIT";
    public static final String MOBILE_NUMBER_ILLEGAL = "isv.MOBILE_NUMBER_ILLEGAL";
    public static final String D_MC = "VALVE:D_MC";
    public static final String H_MC = "VALVE:H_MC";
    public static final String M_MC = "VALVE:M_MC";
    //public static final String ACCOUNT_ABNORMAL = "isv.ACCOUNT_ABNORMAL";
    public static final String AMOUNT_NOT_ENOUGH = "isv.AMOUNT_NOT_ENOUGH";
    //public static final String ACCOUNT_NOT_EXISTS = "isv.ACCOUNT_NOT_EXISTS";
    //public static final String SYSTEM_ERROR = "isv.SYSTEM_ERROR";
    //public static final String SMS_SIGNATURE_ILLEGAL = "isv.SMS_SIGNATURE_ILLEGAL";
    //public static final String SMS_TEMPLATE_ILLEGAL = "isv.SMS_TEMPLATE_ILLEGAL";
    //public static final String TEMPLATE_MISSING_PARAMETERS = "isv.TEMPLATE_MISSING_PARAMETERS";
    //public static final String TEMPLATE_PARAMS_ILLEGAL = "isv.TEMPLATE_PARAMS_ILLEGAL";
    //public static final String PRODUCT_UN_SUBSCRIPT = "isv.PRODUCT_UN_SUBSCRIPT";
    //public static final String MOBILE_COUNT_OVER_LIMIT = "isv.MOBILE_COUNT_OVER_LIMIT";
    //public static final String PARAM_LENGTH_LIMIT = "isv.PARAM_LENGTH_LIMIT";
    //public static final String INVALID_PARAMETERS = "isv.INVALID_PARAMETERS";
    //public static final String FILTER = "isv.FILTER";
    //public static final String PRODUCT_UNSUBSCRIBE = "isv.PRODUCT_UNSUBSCRIBE";
    public static final String BUSINESS_LIMIT_CONTROL = "isv.BUSINESS_LIMIT_CONTROL";
    public static final String OUT_OF_SERVICE = "isv.OUT_OF_SERVICE";
    //public static final String PARAM_NOT_SUPPORT_URL = "isv.PARAM_NOT_SUPPORT_URL";
    //public static final String RAM_PERMISSION_DENY = "isv.RAM_PERMISSION_DENY";
    //public static final String INVALID_JSON_PARAM = "isv.INVALID_JSON_PARAM";
    public static Map<String, String> nationMap = Maps.newHashMap();
    public static String APP_KEY = "1de3af36f5fa8";
    public static String SUCCEED = "200";

    public static void setNationMap(String [] nationArr){
        nationMap.clear();
        for(String nation : nationArr){
            String [] n = nation.split("_");
            if(n == null || n.length < 2)
                continue;

            nationMap.put(n[0], n[1]);
        }
    }

    public static boolean checkCodeVerify(String phoneNum, String zone ,String checkCode){
        String result = com.ideaction.utils.sms.SmsKit.requestData("https://webapi.sms.mob.com/sms/verify",
            "appkey=" + com.ideaction.utils.sms.SmsKit.APP_KEY + "&phone=" + phoneNum + "&zone=" + zone + "&code=" + checkCode);

        return SUCCEED.equals(result);
    }

    public static void main(String[] args) {
        checkCodeVerify("17308102327", "86", "614752");
    }

    /**
     * 发起https 请求
     * @param address
     * @param params
     * @return
     */
    public static String requestData(String address ,String params){

        HttpURLConnection conn = null;
        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
                public X509Certificate[] getAcceptedIssuers(){return null;}
                public void checkClientTrusted(X509Certificate[] certs, String authType){}
                public void checkServerTrusted(X509Certificate[] certs, String authType){}
            }};

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());

            //ip host verify
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return urlHostName.equals(session.getPeerHost());
                }
            };

            //set ip host verify
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            URL url = new URL(address);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");// POST
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            // set params ;post params
            if (params!=null) {
                conn.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.write(params.getBytes(Charset.forName("UTF-8")));
                out.flush();
                out.close();
            }
            conn.connect();
            //get result
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String result = parsRtn(conn.getInputStream());
                return result;
            } else {
//                log.warn(conn.getResponseCode() + " "+ conn.getResponseMessage());
            }
        } catch (Exception e) {
//            log.warn("requestData err", e);
            e.printStackTrace();
        } finally {
            if (conn != null)
                conn.disconnect();
        }
        return null;
    }

    private static String parsRtn(InputStream inputStream) throws IOException, JSONException {
        String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
        JSONObject json = JSONObject.parseObject(result);
        return json.get("status").toString();
    }
}
